package exttable.formgenerator;

import utils.Localisation;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Enumeration;
import java.util.Vector;


/**
 * Created by IntelliJ IDEA.
 * User: ADMIN
 * Date: 06.04.2010
 * Time: 11:29:00
 * To change this template use File | Settings | File Templates.
 */
public class FormGenerator {
    public static Object obj;
    public FormGenerator(String tableName, Object obj) {
        FormGenerator.obj=obj;
        JFrame frame = new JFrame(tableName);
        frame.setTitle("Form to insert");
        frame.setName("Form to insert");
        frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        JPanel panelGrid = new JPanel(new GridLayout());
        panelGrid.setName("panelGrid");
        JPanel panelFlow = new JPanel(new FlowLayout());
        panelFlow.setName("panelFlow");
        panelGrid.add(generatePanel(tableName));
        panelFlow.add(panelGrid);
        JScrollPane jsp = new JScrollPane(panelFlow);
        frame.add(jsp);
        frame.setSize(650, 700);
        frame.setVisible(true);


    }

    public static Object getObj() {
        return obj;
    }

    public static JPanel generatePanel(String tableName) {
        final Vector<String> nameOfColumnForInsert = new Vector<String>();
        final Vector<Object> valueOfColumnForInsert = new Vector<Object>();
        SpringLayout spLayout = new SpringLayout();
        JButton nextButton;
        JPanel mainPanel = new JPanel(spLayout);
        mainPanel.setName("mainPanel");
        final int insertBySystem = ComponentsToPanel.addComponentsFromDB(mainPanel, tableName, getObj() );
        nextButton = new JButton(Localisation.getMessage("form.continue"));
        nextButton.setName(tableName);
        nextButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                if (!isFormFilled(e)) {
                    JOptionPane.showMessageDialog(null, Localisation.getMessage("warring.emptyfields"),
                            Localisation.getMessage("warring.waring"),
                            JOptionPane.WARNING_MESSAGE);
                    return;
                }
                final JFrame myframeForTableInput = new JFrame();

                myframeForTableInput.setTitle("Table of input values");
                myframeForTableInput.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
                nameOfColumnForInsert.clear();
                valueOfColumnForInsert.clear();

                Vector<String> columnName = new Vector<String>();
                columnName.add(Localisation.getMessage("table.column.prameter"));
                columnName.add(Localisation.getMessage("form.analysvalue"));
                Vector<Vector> rowData = new Vector<Vector>();

                JButton sourceButton = (JButton) e.getSource();
                String tableName = sourceButton.getName();
                JPanel parentPanel = (JPanel) sourceButton.getParent().getParent();

                Component[] compArray = parentPanel.getComponents();
                try {
                    ComponentsToPanel.returnRowData(tableName, compArray, nameOfColumnForInsert, valueOfColumnForInsert, rowData);
                } catch (Exception e1) {
                    e1.printStackTrace();  
                }
                JTable tableInput = new JTable(rowData, columnName);
                JPanel resultPanel = new JPanel(new BorderLayout());
                JScrollPane jsp = new JScrollPane(tableInput);
                jsp.setPreferredSize(new Dimension(500, 600));
                resultPanel.add(jsp, BorderLayout.CENTER);
                JButton saveButton = new JButton(Localisation.getMessage("error.save"));
                JButton but = (JButton) e.getSource();
                saveButton.setName(but.getName());

                saveButton.setPreferredSize(new Dimension(30, 20));
                saveButton.addActionListener(ListenerFactory.recordToDB(tableName, nameOfColumnForInsert, valueOfColumnForInsert, myframeForTableInput, insertBySystem, obj));
                resultPanel.add(saveButton, BorderLayout.SOUTH);
                myframeForTableInput.add(resultPanel);


                myframeForTableInput.setVisible(true);
                myframeForTableInput.pack();

            }

        });
        mainPanel.add(new JLabel());
        JPanel panelButton = new JPanel(new BorderLayout());
        panelButton.setName("panelButton");
        panelButton.add(nextButton, BorderLayout.WEST);
        mainPanel.add(panelButton);
        Component[] compArray = mainPanel.getComponents();
        int numPairs = compArray.length / 2;
        //Lay out the panel.
        SpringUtilities.makeCompactGrid(mainPanel,
                numPairs, 2, //rows, cols
                1, 1,        //initX, initY
                1, 1);       //xPad, yPad

        //Set up the content pane.
        mainPanel.setOpaque(true);  //content panes must be opaque
        return mainPanel;
    }

    public static boolean isFormFilled(ActionEvent e) {
        JButton sourceButton = (JButton) e.getSource();
        JPanel parentPanel = (JPanel) sourceButton.getParent().getParent();
        for (int i = 0; i < parentPanel.getComponentCount(); i++) {
            if (parentPanel.getComponent(i) instanceof JTextField) {

                JTextField field = (JTextField) parentPanel.getComponent(i);
                if (field.getName().equals("email")) {
                    continue;
                }
                if (field.getText().trim().length() > 0) {
                    //field.setBackground(Color.white);
                    continue;
                } else {
                    field.setBackground(Color.red);
                    field.setFocusable(true);
                    return false;
                }
            } else if (parentPanel.getComponent(i) instanceof JPanel) {
                JPanel panelSmall = (JPanel) parentPanel.getComponent(i);
                for (int j = 0; j < panelSmall.getComponentCount(); j++) {
                    if (panelSmall.getComponent(j) instanceof JRadioButton) {
                        JRadioButton field = (JRadioButton) panelSmall.getComponent(j);
                        ButtonGroup bg = ((DefaultButtonModel) field.getModel()).getGroup();
                        Enumeration<AbstractButton> en = bg.getElements();

                        while (en.hasMoreElements()) {
                            JRadioButton rb1 = (JRadioButton) en.nextElement();
                            JRadioButton rb2 = (JRadioButton) en.nextElement();
                            if (rb1.isSelected()) {
                                continue;
                            } else if (rb2.isSelected()) {
                                continue;
                            }
                            return false;
                        }

                    } else if (panelSmall.getComponent(j) instanceof JTextField) {
                        JTextField field = (JTextField) panelSmall.getComponent(j);
                        if (field.getName().equals("email")) {
                            continue;
                        }
                        if (field.getText().trim().length() > 0) {
                            field.setBackground(Color.white);
                            continue;
                        } else {
                            field.setBackground(Color.red);
                            field.setFocusable(true);
                            return false;
                        }
                    }

                }
            }
        }

        return true;
    }

}
